// packageAdvance/pages/advanceIndex/advanceIndex.js
import {
    getauditapplyapi,
    getapplylistapi,
    getapplylistallapi
} from '../../api/advance'
import {
    shake,
    alert
} from '../../../utils/util'
import dayjs from 'dayjs'
import user from '../../../utils/user'

Page({
    /**
     * 页面的初始数据
     */
    data: {
        isone: 1,
        jstime: '',
        allapply: [],
        allapply2: [],
        searchkey: '',
        requestnotelist: [],
        pagenum: 1,
        pagesize: 20,
        indexnum: 0,
        showcheck: false,
        selectnum: 0,
        searr: [],
        // 日历
        spotMap: {
            // y2022m5d9: 'deep-spot',
            // y2022m5d10: 'spot',
            // y2022m6d10: 'spot',
            // y2022m7d10: 'spot',
            // y2022m8d10: 'spot',
            // y2022m10d1: 'spot',
            // y2023m5d10: 'spot',
        },
        // 例子，今天之后的日期不能被选中
        // disabledDate({ day, month, year }) {
        //   const now = new Date();
        //   const date = new Date(year, month - 1, day);
        //   return date > now;
        // },
        // 需要改变日期时所使用的字段
        changeTime: '',
        // 存储已经获取过的日期
        dateListMap: [],
        selectlist: [{
            lable: '审核全部',
            value: ''
        }, {
            lable: '待操作',
            value: 0
        }, {
            lable: '审核中',
            value: 2
        }, {
            lable: '一审驳回',
            value: 3
        }, {
            lable: '二审驳回',
            value: 4
        }, {
            lable: '领取全部',
            value: 10
        }, {
            lable: '已领取',
            value: 5
        }, {
            lable: '待领取',
            value: 6
        }, {
            lable: '已停止',
            value: 7
        }, {
            lable: '领取失败',
            value: 8
        }, {
            lable: '进行中',
            value: 9
        }],
        selectindex: '',
        selectnum: 11,
        isokflag: false,
        showpopupflag: false,
        bhremark: '',
        isplsh: false,
        time: '',
        learnadvanceflag: false,
        hasnext: true,
        arr: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    chengpopselect(e) {
        console.log(e)
        this.setData({
            requestnotelist: [],
            hasnext: true,
            selectindex: e.currentTarget.dataset.i
        })
        if (this.data.isplsh) {
            this.getapplylistall()
        } else {
            console.log(333)
            this.getapplylist()
        }
        this.selectComponent('#bottomFrame').hideFrame()
    },
    clickpicker() {
        this.selectComponent('#bottomFrame').showFrame()
    },
    async onLoad(options) {
        await user.waitLogin()
        this.setData({
            jstime: user.cutOffTime,
            time: dayjs().format('YYYY-MM-DD'),
            requestnotelist: [],
            hasnext: true,
            indexnum: 0,
            pagenum: 1,
        })
        if (this.data.isplsh) {
            this.getapplylistall()
        } else {
            this.getapplylist()
        }
    },
    getapplylist() {
        if (this.data.hasnext) {
            getapplylistapi({
                searchText: this.data.searchkey,
                queryApplyDate: this.data.time,
                originStatus: this.data.selectindex,
                pageNum: this.data.pagenum,
                pageSize: 10
            }).then((res) => {
                console.log(res, 'GFDSYG8F7UYAGRSY78')
                if (res.list) {
                    res.list.forEach((ele, i) => {
                        ele.check = true
                        ele.idCardNo = ele.idCardNo.slice(-4)
                        ele.advanceApplyTime = dayjs(ele.advanceApplyTime).format('YYYY/MM/DD HH:mm')
                        if (ele.applyStatus === 0 && ele.auditStatus === null && ele.status === null) {
                            ele.endstatus = 0
                        } else if (ele.applyStatus === 1 && ele.auditStatus === null && ele.status === null) {
                            ele.endstatus = 2
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === null) {
                            ele.endstatus = 2
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === 0) {
                            ele.endstatus = 2
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 1) {
                            ele.endstatus = 5
                        } else if (ele.applyStatus === 2 && ele.auditStatus === null && ele.status === null) {
                            ele.endstatus = 3
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 0) {
                            ele.endstatus = 6
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 2) {
                            ele.endstatus = 7
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 3) {
                            ele.endstatus = 9
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 4) {
                            ele.endstatus = 8
                        } else if (ele.applyStatus === 1 && ele.auditStatus === 2 && ele.status === 0) {
                            ele.endstatus = 4
                        }
                    })
                    console.log(this.data.requestnotelist, res.list, 99099)
                    let arr = this.data.pagenum === 1 ? res.list : this.data.requestnotelist.concat(res.list)
                    this.setData({
                        requestnotelist: arr,
                        hasnext: res.hasNextPage
                    })
                }

            })
        } else {
            return
        }
    },
    changesearchkey(e) {
        if (this.data.isplsh) {
            shake(() => {
                this.setData({
                    searchkey: e.detail.value,
                    requestnotelist: [],
                    hasnext: true
                })
                this.getapplylistall()
            }, 1000)
        } else {
            shake(() => {
                this.setData({
                    searchkey: e.detail.value,
                    requestnotelist: [],
                    hasnext: true
                })
                console.log(222)
                this.getapplylist()
            }, 1000)
        }
    },
    // bindPickerChange(e) {
    //     this.setData({
    //         requestnotelist: [],
    //         hasnext: true,
    //         selectindex: e.detail.value * 1
    //     })
    //     if (this.data.isplsh) {
    //         this.getapplylistall()
    //     } else {
    //         console.log(333);
    //         this.getapplylist()
    //     }
    // },
    sureoption() {
        if (this.data.selectnum === 0) {
            wx.showToast({
                title: '请选择预支单',
                icon: 'none'
            })
            return
        }
        this.getauditapply(this.data.searr)
    },
    closepopup() {
        this.setData({
            showpopupflag: false
        })
    },
    tgbtn() {
        let num = 0
        this.data.allapply.forEach((ele) => {
            if (ele.check === true) {
                num += 1
                this.data.searr.push(ele.id)
            } else {
                this.data.arr.push(ele.id)
            }
        })
        this.setData({
            selectnum: num,
            isokflag: true,
            showpopupflag: true,
        })
    },
    bhbtn() {
        let num = 0
        this.data.allapply.forEach((ele) => {
            if (ele.check === true) {
                num += 1
                this.data.searr.push(ele.id)
            } else {
                this.data.arr.push(ele.id)
            }
        })
        this.setData({
            selectnum: num,
            isokflag: false,
            showpopupflag: true,
            bhremark: ''
        })
    },
    getapplylistall() {
        getapplylistallapi({
            searchText: this.data.searchkey,
            queryApplyDate: this.data.time,
            applyStatus: 0
        }).then((res) => {
            console.log(this.flat(res), 111111111)
            let arr = this.flat(res)
            arr.forEach((ele, index) => {
                ele.check = true
                ele.idCardNo = ele.idCardNo.slice(-4)
                let date = dayjs(ele.advanceApplyTime).parse('YYYYMMDDHHmmss')
                ele.advanceApplyTime = dayjs(date).format('YYYY/MM/DD HH:mm')
                if (ele.applyStatus === 0 && ele.auditStatus === null && ele.status === null) {
                    ele.endstatus = 0
                } else if (ele.applyStatus === 1 && ele.auditStatus === null && ele.status === null) {
                    ele.endstatus = 2
                } else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === null) {
                    ele.endstatus = 2
                } else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === 0) {
                    ele.endstatus = 2
                } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 1) {
                    ele.endstatus = 5
                } else if (ele.applyStatus === 2 && ele.auditStatus === null && ele.status === null) {
                    ele.endstatus = 3
                } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 0) {
                    ele.endstatus = 6
                } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 2) {
                    ele.endstatus = 7
                } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 3) {
                    ele.endstatus = 9
                } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 4) {
                    ele.endstatus = 8
                } else if (ele.applyStatus === 1 && ele.auditStatus === 2 && ele.status === 0) {
                    ele.endstatus = 4
                }
            })
            console.log(this.chunkArray(arr, 10)[this.data.indexnum], 1111)
            this.setData({
                allapply2: this.chunkArray(arr, 10) ?? [],
                allapply: arr,
                requestnotelist: this.chunkArray(arr, 10)[this.data.indexnum] ?? []
            })
            console.log(this.data.allapply)
            console.log(this.data.allapply2)
        })
    },
    chunkArray(array, chunkSize) {
        let chunks = []
        for (let i = 0; i < array.length; i += chunkSize) {
            chunks.push(array.slice(i, i + chunkSize))
        }
        return chunks
    },
    flat(arr) {
        const result = []
        const stack = [].concat(arr) // 将数组元素拷贝至栈，直接赋值会改变原数组
        // 如果栈不为空，则循环遍历
        while (stack.length !== 0) {
            const val = stack.pop()
            if (Array.isArray(val)) {
                stack.push(...val) // 如果是数组再次入栈，并且展开了一层
            } else {
                result.unshift(val) // 如果不是数组就将其取出来放入结果数组中
            }
        }
        return result
    },

    showcheck() {
        this.setData({
            showcheck: true,
            isplsh: true,
            indexnum: 0,
            requestnotelist: [],
            arr: [],
            selectnum: 0
        })
        this.getapplylistall()
    },
    close() {
        wx.setStorageSync('haslearnadvance', 'true')
        this.setData({
            learnadvanceflag: false
        })
    },
    closetolearn() {
        wx.setStorageSync('haslearnadvance', 'true')
        this.setData({
            learnadvanceflag: false
        })
    },
    edit() {
        console.log(111)
        this.setData({
            showcheck: false,
            isplsh: false,
            pagenum: 1,
            hasnext: true,
            requestnotelist: [],
            arr: []
        })
        console.log(444)
        this.getapplylist()
    },
    todetail(e) {
        console.log(e)
        wx.navigateTo({
            url: '/packageAdvance/pages/advanceDetail/advanceDetail?id=' + e.currentTarget.dataset.id,
        })
    },
    chengeselect(e) {
        console.log(e)
        let id = e.currentTarget.dataset.id
        const index = this.data.allapply.findIndex(i => i.id === id)
        console.log(index)
        if (index !== -1) {
            const bl = !this.data.allapply[index].check
            this.data.allapply[index].check = bl
        }
        this.setData({
            allapply2: this.data.allapply2,
            allapply: this.data.allapply
        })
        console.log(this.data.allapply)
        console.log(this.data.allapply2)
    },
    changebhremark(e) {
        console.log(e)
        this.setData({
            bhremark: e.detail.value
        })
    },
    getauditapply(arr) {
        let obj = null
        if (this.data.isokflag) {
            obj = {
                ids: arr,
                applyStatus: 1,
                isSelectAll: this.data.arr.length === 0 ? 1 : 0
            }
        } else {
            obj = {
                ids: arr,
                applyStatus: 2,
                isSelectAll: this.data.arr.length === 0 ? 1 : 0,
                operRemark: this.data.bhremark
            }
        }
        getauditapplyapi(obj).then((res) => {
            console.log(res)
            if (res) {
                wx.showToast({
                    icon: 'none',
                    title: '操作成功',
                })
                this.setData({
                    showpopupflag: false,
                    showcheck: false,
                    isplsh: false,
                    pagenum: 1,
                    indexnum: 0,
                    arr: [],
                    searr: [],
                    hasnext: true,
                })
                this.getapplylistall()
                this.getapplylist()
            }
        })
    },
    // 日历组件方法
    // 获取日期数据，通常用来请求后台接口获取数据
    getDateList({
        detail
    }) {
        // 检查是否已经获取过该月的数据
        if (this.filterGetList(detail)) {
            // 获取数据
            console.log(detail, '获取数据')
        }
    },
    // 过滤重复月份请求的方法
    filterGetList({
        setYear,
        setMonth
    }) {
        const dateListMap = new Set(this.data.dateListMap)
        const key = `y${setYear}m${setMonth}`
        if (dateListMap.has(key)) {
            return false
        }
        dateListMap.add(key)
        this.setData({
            dateListMap: [...dateListMap],
        })
        return true
    },
    // 日期改变的回调
    selectDay({
        detail
    }) {
        console.log(detail, this.data.isplsh, this.data.isone, 'selectDay detail')
        this.setData({
            pagenum: 1
        })
        if (this.data.isplsh) {
            this.setData({
                requestnotelist: [],
                hasnext: true,
                indexnum: 0,
                pagenum: 1,
                time: dayjs(detail.year + '-' + detail.month + '-' + detail.day).format('YYYY-MM-DD')
            })
            this.getapplylistall()
        } else {
            if (this.data.isone === 1) {
                this.data.isone += 1
                return
            } else {
                this.setData({
                    requestnotelist: [],
                    hasnext: true,
                    indexnum: 0,
                    time: dayjs(detail.year + '-' + detail.month + '-' + detail.day).format('YYYY-MM-DD')
                })
                console.log(999)
                this.getapplylist()
            }
        }
    },
    // 展开收起时的回调
    openChange({
        detail
    }) {
        console.log(detail, 'openChange detail')
    },
    changetime() {
        this.setData({
            changeTime: '2022/1/1',
        })
    },
    extractValues(data) {
        return data.map(subArray => subArray.map(obj => obj.id))
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        if (wx.getStorageSync('haslearnadvance')) {
            this.setData({
                learnadvanceflag: false
            })
        } else {
            this.setData({
                learnadvanceflag: true
            })
        }
        await user.waitLogin()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        await user.waitLogin()
        this.setData({
            jstime: user.cutOffTime,
            requestnotelist: [],
            hasnext: true,
            indexnum: 0,
            pagenum: 1,
        })
        if (this.data.isplsh) {
            this.getapplylistall()
            wx.stopPullDownRefresh()
        } else {
            this.getapplylist()
            wx.stopPullDownRefresh()
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        console.log(this.data.isplsh)
        if (this.data.isplsh) {
            if (this.data.indexnum <= this.data.allapply2.length) {
                this.data.indexnum += 1
                if (this.data.allapply2[this.data.indexnum]) {
                    this.setData({
                        indexnum: this.data.indexnum,
                        requestnotelist: this.data.requestnotelist.concat(this.data.allapply2[this.data.indexnum])
                    })
                }
            } else {
                return
            }
        } else {
            this.setData({
                pagenum: this.data.pagenum + 1
            })
            console.log(777)
            this.getapplylist()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})